<template>
  <div class="graph-container">
    <div v-if="isLoading" class="loading-overlay">正在加载...</div>
    <div ref="container" class="g6-container"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import G6 from '@antv/g6';
import { useGraphStore } from '../stores/graphStore';
import { storeToRefs } from 'pinia';

const container = ref(null);
const store = useGraphStore();
const { graphData, isLoading } = storeToRefs(store);
let graph = null;

onMounted(() => {
  if (container.value) {
    const width = container.value.scrollWidth;
    const height = container.value.scrollHeight || 600;
    
    graph = new G6.Graph({
      container: container.value,
      width,
      height,
      layout: {
        type: 'force',
        preventOverlap: true,
        linkDistance: 150,
      },
      modes: {
        default: ['drag-canvas', 'zoom-canvas', 'drag-node'],
      },
      defaultNode: {
        size: 40,
        style: {
          lineWidth: 2,
          stroke: '#5B8FF9',
        },
        labelCfg: {
          style: {
            fill: '#000',
            fontSize: 10,
          },
        },
      },
      defaultEdge: {
        style: {
          stroke: '#aaa',
          lineWidth: 1,
        },
        labelCfg: {
            autoRotate: true,
            style: {
                fill: '#555',
                fontSize: 10
            }
        }
      },
    });

    // 监听节点点击事件
    graph.on('node:click', (evt) => {
      const { item } = evt;
      const nodeId = item.getID();
      store.expandNode(nodeId);
    });

    // 初始加载数据
    if(store.nodes.length === 0) {
        store.fetchInitialGraph();
    } else {
        graph.data(JSON.parse(JSON.stringify(graphData.value)));
        graph.render();
    }
  }
});

onUnmounted(() => {
  if (graph) {
    graph.destroy();
  }
});

// 监听Pinia中数据的变化，并更新G6图
watch(graphData, (newData) => {
  if (graph) {
    // 使用 changeData 而不是 data 来获得更好的性能和过渡效果
    graph.changeData(JSON.parse(JSON.stringify(newData)));
  }
}, { deep: true });

</script>

<style scoped>
.graph-container {
  position: relative;
  width: 100%;
  height: 100%;
  border: 1px solid #ddd;
  background-color: #fdfdfd;
}
.g6-container {
  width: 100%;
  height: 100%;
}
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
  font-size: 1.5em;
  color: #333;
}
</style>